import json
 
# JSON 字符串
json_string = '{"name": "Alice", "age": 25, "is_student": false, "skills": ["Python", "Machine Learning"]}'
 
# 转换为 Python 对象
data = json.loads(json_string)
 
print(data)  # 输出：{'name': 'Alice', 'age': 25, 'is_student': False, 'skills': ['Python', 'Machine Learning']}
print(type(data))  # 输出：<class 'dict'>


import json
 
# Python 对象
python_obj = {
    "name": "Bob",
    "age": 30,
    "is_student": True,
    "skills": ["JavaScript", "React"]
}
 
# 转换为 JSON 字符串
json_data = json.dumps(python_obj)
 
print(json_data)  # 输出：{"name": "Bob", "age": 30, "is_student": true, "skills": ["JavaScript", "React"]}
print(type(json_data))  # 输出：<class 'str'>


import json
 
# 从文件中加载 JSON 数据
with open("data.json", "r") as file:
    data = json.load(file)
 
print(data)  # 输出：{'name': 'Charlie', 'age': 35, 'is_student': False, 'courses': ['Math', 'Physics']}



import json
 
# Python 对象
data = {
    "name": "Diana",
    "age": 28,
    "is_student": True,
    "subjects": ["English", "History"]
}
 
# 写入到 JSON 文件
with open("output.json", "w") as file:
    json.dump(data, file)
 
print("数据已写入到 output.json")




import json
 
data = {"name": "Eve", "age": 22, "skills": ["Python", "Data Science"]}
 
# 美化输出
formatted_json = json.dumps(data, indent=4)
print(formatted_json)












import json
from datetime import datetime
 
# 自定义对象
class User:
    def __init__(self, name, age, joined_at):
        self.name = name
        self.age = age
        self.joined_at = joined_at
 
# 自定义序列化函数
def custom_serializer(obj):
    if isinstance(obj, datetime):
        return obj.isoformat()  # 将 datetime 转换为 ISO 格式
    if isinstance(obj, User):
        return {"name": obj.name, "age": obj.age, "joined_at": obj.joined_at.isoformat()}
    raise TypeError("类型不支持序列化")
 
user = User("Frank", 40, datetime.now())
 
# 转换为 JSON
json_data = json.dumps(user, default=custom_serializer, indent=4)
print(json_data)



import json
 
invalid_json = '{"name": "Grace", "age": 29,}'  # 末尾多了一个逗号
 
try:
    data = json.loads(invalid_json)
except json.JSONDecodeError as e:
    print("JSON 解析错误：", e)

